//
//  LoginViewController.m
//  inquiry
//
//  Created by 高宇 on 2020/5/18.
//  Copyright © 2020 高宇. All rights reserved.
//

#import "LoginViewController.h"
#import "RegisterViewController.h"
#import "HomeViewController.h"
#import "MyViewController.h"
#import "Interface.h"
#import "ULNetHelper.h"
#import "GXToast.h"
#import "NSString+MD5.h"
#import "TeacherViewController.h"
#import "CompleteViewController.h"

@interface LoginViewController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *numberTF;
@property (weak, nonatomic) IBOutlet UITextField *passwordTF;
@property (weak, nonatomic) IBOutlet UIButton *loginButton;
@property (weak, nonatomic) IBOutlet UIButton *registerButton;

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.numberTF.delegate = self;
    self.passwordTF.delegate = self;
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    return [textField resignFirstResponder];
}


- (IBAction)loginClick:(UIButton *)sender {
    if ([self.numberTF.text isEqualToString:@""]) {
        [GXToast showText:@"请填写身份证"];
        return;
    }else if ([self.passwordTF.text isEqualToString:@""]) {
        [GXToast showText:@"请填写密码"];
        return;
    }
    
    self.loginButton.enabled = NO;
    
    NSString *time = [self nowTimeSwitchTimestamp];
    NSString *password = [self.passwordTF.text MD5];
    NSString *token = [[NSString stringWithFormat:@"%@-%@-1000",password,time] MD5];
    NSDictionary *dic = @{
        @"userName":self.numberTF.text,
        @"password":password,
        @"token":token,
        @"time":time,
    };
    [ULNetHelper POST:loginPath parameters:dic success:^(id responseObject) {
        self.loginButton.enabled = YES;
        NSMutableDictionary *dic = [responseObject[@"data"] mutableCopy];
        long code = [responseObject[@"code"] longValue];
        if (code == 200) {
            NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
            
            //学生
            if ([dic[@"type"] intValue] == 1001) {
                
                NSString *studentName = dic[@"studentName"];
                if (studentName.length <= 0) {
                    //如果学生角色没有填写详情资料   跳转页面
                    CompleteViewController *vc = [[CompleteViewController alloc] init];
                    vc.modalPresentationStyle =  UIModalPresentationFullScreen;
                    vc.identityId = dic[@"uuid"];
                    [self presentViewController:vc animated:YES completion:nil];
                    return;
                }
                
                [user setObject:dic[@"uuid"] forKey:@"uuid"];
                [user setObject:dic[@"studentName"] forKey:@"studentName"];
                [user setObject:self.passwordTF.text forKey:@"password"];
                [user setObject:dic[@"type"] forKey:@"type"];
                [user setObject:dic[@"identityId"] forKey:@"identityId"];
                [user setInteger:[dic[@"gradeId"] intValue] forKey:@"gradeId"];
                [user setInteger:[dic[@"schoolId"] intValue] forKey:@"schoolId"];
                [user setInteger:[dic[@"classesId"] intValue] forKey:@"classesId"];
                [user setObject:dic[@"userInfo"] forKey:@"userInfo"];
                //修改主视图逻辑
                HomeViewController *vc = [[HomeViewController alloc] init];
                UINavigationController *nc = [[UINavigationController alloc] initWithRootViewController:vc];
                nc.tabBarItem.selectedImage = [[UIImage imageNamed:@"矩形(4)-1"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
                nc.tabBarItem.image = [[UIImage imageNamed:@"矩形(1)-1"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
                nc.tabBarItem.title = @"测试";

                MyViewController *myvc = [[MyViewController alloc] init];
                UINavigationController *mync = [[UINavigationController alloc] initWithRootViewController:myvc];
                mync.tabBarItem.selectedImage = [[UIImage imageNamed:@"矩形(2)"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
                mync.tabBarItem.image = [[UIImage imageNamed:@"矩形(5)-1"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
                mync.tabBarItem.title = @"我的";

                UITabBarController *tab=[[UITabBarController alloc] init];
                tab.viewControllers=@[nc,mync];
                UIWindow *window = [UIApplication sharedApplication].keyWindow;
                window.rootViewController = tab;
            }else{
                [user setInteger:[dic[@"gradeId"] intValue] forKey:@"gradeId"];
                [user setInteger:[dic[@"schoolId"] intValue] forKey:@"schoolId"];
                [user setInteger:[dic[@"classesId"] intValue] forKey:@"classesId"];
                [user setObject:dic[@"type"] forKey:@"type"];
                [user setObject:self.numberTF.text forKey:@"identityId"];
                [user setObject:dic[@"teacherId"] forKey:@"teacherId"];
                [user setObject:dic[@"teacherName"] forKey:@"teacherName"];
                [user setObject:[self getNowTimeTimestamp] forKey:@"teacherLoginTime"];
                
                
                //老师页面
                TeacherViewController *vc = [[TeacherViewController alloc] init];
                UINavigationController *tab = [[UINavigationController alloc] initWithRootViewController:vc];
                UIWindow *window = [UIApplication sharedApplication].keyWindow;
                window.rootViewController = tab;
            }
            
        }else{
            
            NSString *msg = responseObject[@"msg"];
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"登录失败" message: msg preferredStyle:UIAlertControllerStyleAlert];
            [alert addAction:[UIAlertAction actionWithTitle:@"关闭" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {

            }]];
            [alert addAction:[UIAlertAction actionWithTitle:@"重试" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                [self loginClick:nil];
            }]];
            [self presentViewController:alert animated:YES completion:nil];

        }
    } failure:^(NSError *error) {
        self.loginButton.enabled = YES;
        [GXToast showText:@"网络连接失败"];
    }];
    
    
}

- (IBAction)registerClick:(id)sender {
    RegisterViewController *vc = [[RegisterViewController alloc] init];
    vc.modalPresentationStyle =  UIModalPresentationFullScreen;
    [self presentViewController:vc animated:YES completion:nil];
}

//获取当前时间戳 （以毫秒为单位）
//返回值格式:1555642454396
//这里注意要获取完全部数值后在(long)强转, 如果(long)[datenow timeIntervalSince1970]*1000 这么写是先强转在*1000,就是秒级别的数据了
- (NSString *)nowTimeSwitchTimestamp{
    NSDate *datenow = [NSDate date];//现在时间
    //这里如果long不够用,就用(long long)
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)([datenow timeIntervalSince1970]*1000)];
    return timeSp;
}

//返回值格式:2019-04-19 10:33:35.886
- (NSString *)getNowTimeTimestamp{
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    [formatter setTimeZone:[NSTimeZone timeZoneWithName:@"Asia/Beijing"]];
    NSString *dateString      = [formatter stringFromDate: datenow];
    NSLog(@"当前时间戳对应的时间是:%@",dateString);
    return dateString;
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
